Ext.define('Monkey.view.main.ViewportController', {
    extend: 'Monkey.view.BaseController',
    alias: 'controller.ctrl-mainviewport',

    init: function () {
        this.initialViews();
    },

    initialViews: function () {
        var navigation = this.getReferences().navigation;
        this.request(Monkey.URL.LOAD_CHILD_MENUS + '?fields=id,name,icon', 'GET', {parentId: Monkey.Config.menuRootId}, function (data) {
            Ext.each(data.data, function (menu) {
                navigation.add({
                    title: menu.name,
                    //iconCls: menu.iconCls,
                    icon: menu.icon,
                    xtype: 'treepanel',
                    lines: false,
                    rootVisible: false,
                    displayField: 'name',
                    store: Ext.create('Monkey.store.BaseTreeStore', {
                        nodeParam: 'parentId',
                        defaultRootId: menu.id,
                        root: {
                            expanded: true
                        },
                        proxy: {
                            type: 'ajax',
                            url: Monkey.URL.LOAD_CHILDREN_MENUS,
                            extraParams: {
                                fields: 'id,leaf,name,parentId,icon,weight,view'
                            },
                            reader: 'json'
                        }
                    }),
                    listeners: {
                        itemclick: 'setCurrentView'
                    }
                });
            });
        });
    },

    logout: function () {
        var me = this;
        Ext.Msg.show({
            title: '请确认',
            message: '注销并安全退出系统吗？',
            buttons: Ext.Msg.OKCANCEL,
            fn: function (buttonId) {
                if (buttonId == 'ok') {
                    me.request(Monkey.URL.LOGOUT_URL, 'GET', null, function () {
                        me.toLoginPage();
                    });
                }
            },
            icon: Ext.Msg.INFO
        });

    },

    setCurrentView: function (cmp, record, item, index, e, eOpts) {
        var viewId = 'Monkey-Tab-' + record.data.id,
            mainTabPanel = this.getReferences().mainTabPanel;

        var view = mainTabPanel.getComponent(viewId);
        if (Ext.isEmpty(view)) {
            view = Ext.create('Monkey.view.' + record.data.view, {
                itemId: viewId,
                title: record.data.name,
                closable: true,
                icon: record.data.icon,
                html: viewId
            });
            mainTabPanel.add(view);
        }
        mainTabPanel.setActiveTab(view);
    }

});
